/*
 * @Descripttion:
 * @version: 1.0.0
 * @Author: liuzicheng
 * @Date: 2025-01-22 13:48:44
 * @LastEditors: liuzicheng
 * @LastEditTime: 2025-02-17 11:43:10
 */
import { MouseEvent, useEffect, useRef } from "react";
const SwitchThemeAnimate: React.FC<{ setIsDark: (args: boolean) => void }> = (props) => {
  let theme = "";
  const switchIconRef = useRef<HTMLDivElement>(null);
  const { setIsDark } = props;
  const currentTheme = useRef(sessionStorage.getItem("isDark") === "true");
  const changeTheme = (e: MouseEvent) => {
    if (!currentTheme.current) {
      switchIconRef.current.style.transform = "translateX(18px)";
      theme = "dark";
    } else {
      theme = "";
      switchIconRef.current.style.transform = "translateX(0px)";
    }
    toggleDark(e);
  };
  const isAppearanceTransition = () => {
    return document.startViewTransition && !window.matchMedia("(prefers-reduced-motion: reduce)").matches;
  };
  useEffect(() => {
    document.documentElement.setAttribute("class", currentTheme.current ? "dark" : "");
    if (currentTheme.current) {
      switchIconRef.current.style.transform = "translateX(18px)";
    }
  }, []);
  const changeStatusAndtheme = () => {
    currentTheme.current = !currentTheme.current;
    setIsDark(currentTheme.current);
    sessionStorage.setItem("isDark", currentTheme.current ? "true" : "false");
    document.documentElement.setAttribute("class", theme);
  };

  function toggleDark(event?: MouseEvent) {
    if (!isAppearanceTransition() || !event) {
      changeStatusAndtheme();
      return;
    }
    const x = event?.clientX;
    const y = event?.clientY;
    const endRadius = Math.hypot(Math.max(x ?? 0, innerWidth - (x ?? 0)), Math.max(y ?? 0, innerHeight - (y ?? 0)));
    const transition = document.startViewTransition(async () => {
      changeStatusAndtheme();
    });
    transition.ready.then(() => {
      const clipPath = [`circle(0px at ${x}px ${y}px)`, `circle(${endRadius}px at ${x}px ${y}px)`];
      document.documentElement.animate(
        {
          clipPath: !currentTheme.current ? [...clipPath].reverse() : clipPath
        },
        {
          duration: 400,
          easing: "ease-in",
          pseudoElement: !currentTheme.current ? "::view-transition-old(root)" : "::view-transition-new(root)"
        }
      );
    });
  }

  return (
    <button className="switch-theme " onClick={changeTheme}>
      <span className="check f-c-c" ref={switchIconRef}>
        {currentTheme.current ? (
          <span className="i-ic:outline-wb-sunny "></span>
        ) : (
          <span className="i-ic:outline-dark-mode "></span>
        )}
      </span>
    </button>
  );
};
export default SwitchThemeAnimate;
